let isSkips = true;
// 逻辑处理
export const handleLogicData = (metaData, pageData, handleItem) => {
  metaData.forEach((item) => {
    if (typeof item.show === "string") item.show = "false";
  });
  const logicResList = JSON.parse(pageData.metaInfo)?.surveyLogic || JSON.parse(pageData.metaInfo)?.enrollLogic || {};
  const optionRelList = logicResList.optionRelList || [];
  const questionRelList = logicResList.questionRelList || [];
  getBool(metaData, questionRelList, "question", handleItem);
  getBool(metaData, optionRelList, "option", handleItem);
  isSkips = true;
};
/** 条件判断
 * params{metaData, list, type, handleItem}
 * metaData 元数据
 * list 规则列表
 * type类型{题目关联和选项关联}
 * handleItem 最近操作的题目
 */
const getBool = (metaData, list, type, handleItem) => {
  list.forEach((item) => {
    // 先检索条件是否满足
    let booleans = "";
    item.conditions.forEach((cond) => {
      let questionId = Array.isArray(cond.questionId)
        ? cond.questionId[0]
        : cond.questionId;
      let obj = metaData.filter((mate) => mate.orderId === questionId)[0];
      if (!obj) return;
      let values = []; // 存题目值
      if (!Array.isArray(obj.value)) obj.value && values.push(obj.value);
      else values = obj.value;
      let ic = { or: "||", and: "&&", if: "" };
      let logic = ic[cond.logic] || "";
      if (cond.status) booleans += logic + handle[cond.status](obj, values, cond); // obj 题目信息 cond 规则信息 values存题目值
    });
    /** 根据条件择执行操作
     * params{metaData, item.results, type, !!eval(boolean), handleItem}
     * metaData 元数据
     * item.results 执行题目
     * type类型{题目关联和选项关联}
     * !!eval(booleans) 规则是否满足
     * handleItem 最近操作的题目
     * 规则id集合
     */
    let start = booleans.substring(0, 2);
    if (["&&", "||"].includes(start)) booleans = booleans.substring(2);
    buildData(
      metaData,
      item.results,
      type,
      !!eval(booleans),
      handleItem,
      item.conditions.map((row) => row.questionId)
    );
  });
};
// 规则集合 obj 题目信息 values存题目值 cond 规则信息
const handle = {
  // 获取对应值
  getVal: (obj, values, cond) => {
    let index = null;
    cond.options.forEach((item, idx) => {
      if (item.label === cond.questionId[1]) index = idx;
    });
    return index === null ? values : [values[index]];
  },
  // 评分条件判断
  rateBool: (obj, values, cond) => {
    let val = handle.getVal(obj, values, cond);
    if (JSON.stringify(values) === "[]") return false;
    return (val || []).some(
      (val) => Number(cond.minRate) <= val && val <= Number(cond.maxRate)
    );
  },
  // 选中
  selected: (obj, values, cond) => {
    if (obj.itemType === "rate") {
      return handle.rateBool(obj, values, cond);
    }
    const label =
      (cond.options || []).filter((opt) => opt.value === cond.optionValue)[0]
        ?.label || null;
    return values.includes(label);
  },
  // 未选中
  unSelected: (obj, values, cond) => {
    if (obj.itemType === "rate") {
      return !handle.rateBool(obj, values, cond);
    }
    const label =
      (cond.options || []).filter((opt) => opt.value === cond.optionValue)[0]
        ?.label || null;
    return !values.includes(label);
  },
  // 显示
  show: (obj) => {
    return !!obj.show;
  },
  // 未显示
  unShow: (obj) => {
    return !obj.show;
  },
  // 已答
  answer: (obj, values) => {
    return (values.length !== 0) & (values[0] !== "");
  },
  // 未答
  unAnswer: (obj, values) => {
    return values.length === 0 || values[0] === "";
  },
  // 等于
  EQ: (obj, values, cond) => {
    let val = handle.getVal(obj, values, cond);
    if (JSON.stringify(val) === "[]") return "false";
    // 全部等于
    return (val || []).some((val) => val === Number(cond.number));
  },
  // 小于
  LT: (obj, values, cond) => {
    let val = handle.getVal(obj, values, cond);
    if (JSON.stringify(val) === "[]") return "false";
    // 全部小于
    return (val || []).some((val) => val < Number(cond.number));
  },
  // 大于
  GT: (obj, values, cond) => {
    let val = handle.getVal(obj, values, cond);
    if (JSON.stringify(val) === "[]") return "false";
    // 全部小于
    return (val || []).some((val) => val > Number(cond.number));
  },
  // 介于
  BTW: (obj, values, cond) => {
    let val = handle.getVal(obj, values, cond);
    if (JSON.stringify(val) === "[]") return "false";
    // 全部介于
    return (val || []).some(
      (val) => Number(cond.minRate) < val && val < Number(cond.maxRate)
    );
  }
};
// 执行集合
const execute = {
  // 选项关联
  option: (metaData, result, boole) => {
    // 选择题目 有操作进来
    result.forEach((item) => {
      const list = (item.options || [])
        .filter((opt) => item.optionValue.includes(opt.value))
        .map((opt) => opt.label);
      metaData.forEach((mate) => {
        if (item.questionId === mate.orderId) {
          // 展示选项
          mate.itemOptResList.forEach((itemOption) => {
            if (list.includes(itemOption.optionName)) itemOption.show = boole;
          });
        }
      });
    });
  },
  // 题目关联
  question: (metaData, result, boole, handleItem, ruleIds) => {
    result.forEach((item) => {
      execute[item.operation](metaData, item, boole, handleItem, ruleIds);
    });
  },
  // 选项 显示不显示
  show: (metaData, item, boole) => {
    let obj = metaData.filter((mate) => mate.orderId === item.questionId)[0];
    if (!obj) return;
    obj.show = boole;
  },
  // 题目关联 跳转 item 要跳到的题目 boole 条件是否满足 handleItem 操作的题目undefined为首次进入 ruleIds条件id集合
  skip: (metaData, item, boole, handleItem, ruleIds) => {
    let startIdx = null;
    let endIdx = null;
    if (
      (handleItem && (ruleIds || []).includes(handleItem.orderId)) ||
      (!handleItem && boole)
    ) {
      // 操作后 或者首次进入条件满足的情况
      let endId = ruleIds.pop();
      metaData.forEach((mate, index) => {
        if (mate.orderId === endId) startIdx = index;
        if (mate.orderId === item.questionId) endIdx = index;
        if (isSkips && startIdx !== null && index > startIdx) mate.show = true; // 将操作题后面的都显示一次
      });
      isSkips = false; // 关闭 禁止二次将操作题后面显示
      if (item.questionId === "end") endIdx = metaData.length; // 如果是跳到结束 就将endIdx设置成最大
      // 条件满足 进行跳题
      if (boole) {
        for (let i = startIdx + 1; i < endIdx; i++) {
          metaData[i].show = false;
        }
      }
    }
  }
};
// 执行方法
const buildData = (metaData, result, type, boole, handleItem, ruleIds) => {
  execute[type](metaData, result, boole, handleItem, ruleIds);
};

// 隐藏没有选项的题目
export const hideQuestionsWithoutOption = (question) => {
  let option = question.itemOptResList || [];
  if (option.length > 0) {
    return option.every((item) => item.show === false);
  } else {
    return false;
  }
};
